package com.example.rabbit.config;

import cn.hutool.core.util.EnumUtil;
import com.example.rabbit.BeanUtils;
import com.example.rabbit.enums.TopicEnum;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;

import javax.annotation.PostConstruct;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * topic交换机
 */
@Configuration
@DependsOn({"beanUtils"})
public class TopicConfig {

    /**
     * 消息存活时间
     */
    private final static String xMessageTt = "x-message-ttl";

    @PostConstruct
    public void topicExchange() {
        TopicExchange topicExchange;
        Queue queue;
        LinkedHashMap<String, TopicEnum> map = EnumUtil.getEnumMap(TopicEnum.class);
        for (Map.Entry<String, TopicEnum> entry : map.entrySet()) {
            topicExchange = new TopicExchange(entry.getValue().getExchange());
            queue = new Queue(entry.getValue().getQueue());
            if (entry.getValue().getTtl() != null) {
                queue.addArgument(xMessageTt, entry.getValue().getTtl());
            }
            BeanUtils.registerBean(entry.getValue().getExchange(), topicExchange);
            BeanUtils.registerBean(entry.getValue().getQueue(), queue);
            BeanUtils.registerBean(entry.getKey(), BindingBuilder.bind(queue).to(topicExchange).with(entry.getValue().getRoutingKey()));
        }
    }
}
